#include <hexstr.h>

int cvtHex2str(const char *hexptr, int hexsize, char *outstr, int outsize)
{
    static const char DEV_C51_CODE_FLAG *hexCvtStr = "0123456789ABCDEF";
    int i;
    uint8_t tmpid;
    if (!(hexptr && outstr && hexsize > 0 && outsize > 0))
    {
        return 0;
    }
    if (outsize / 2 < hexsize)
    {
        // logwarnc("%d < %d", outsize, hexsize * 2);
        hexsize = outsize / 2;
    }
    for (i = 0; i < hexsize; i++)
    {
        tmpid = hexptr[i];
        outstr[i * 2] = hexCvtStr[(tmpid >> 4) & 0xf];
        outstr[i * 2 + 1] = hexCvtStr[(tmpid >> 0) & 0xf];
    }
    if (hexsize * 2 < outsize)
    {
        outstr[hexsize * 2] = 0;
    }
    return hexsize * 2;
}
static uint8_t charToHexVal(uint8_t hexchar)
{
    uint8_t tmphex = 0;
    if (hexchar >= '0' && hexchar <= '9')
    {
        tmphex = (hexchar - '0');
    }
    else if (hexchar >= 'a' && hexchar <= 'f')
    {
        tmphex = (hexchar - 'a' + 10);
    }
    else if (hexchar >= 'A' && hexchar <= 'F')
    {
        tmphex = (hexchar - 'A' + 10);
    }
    else
    {
        tmphex = 0;
    }
    return tmphex;
}
int cvtStr2hex(const char *instr, int insize, char *hexptr, int hexsize)
{
    // char tmphexstr[3] = {0};
    int i;
    if (!(hexptr && insize && hexsize > 0 && insize > 0))
    {
        return 0;
    }
    if (hexsize * 2 < insize)
    {
        // logwarnc("%d * 2 < %d", hexsize, insize);
        insize = hexsize * 2;
    }
    hexsize = insize / 2;
    for (i = 0; i < hexsize; i++)
    {
        // tmphexstr[0] = instr[i * 2];
        // tmphexstr[1] = instr[i * 2 + 1];
        // hexptr[i] = strtol(tmphexstr, NULL, 16);
        hexptr[i] = (charToHexVal(instr[i * 2]) << 4) + charToHexVal(instr[i * 2 + 1]);
    }
    return hexsize;
}

